package com.aliware.tianchi.loadbalance;


import com.aliware.tianchi.common.TianchiRpcContants;
import org.apache.dubbo.rpc.RpcContext;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author lorne
 * @date 2019/6/25
 * @description
 */
public class BaseScore {

    private double nowAvg = 1;

    private double concurrency;

    private AtomicLong time = new AtomicLong();

    private List<Long> timeList = new CopyOnWriteArrayList<>();

    private List<Long> times = new CopyOnWriteArrayList<>();

    private List<Double> concurrencys = new CopyOnWriteArrayList<>();

    public BaseScore(int threads) {
        this.concurrency = threads;
    }

    public double getNowAvg() {
        return nowAvg;
    }

    public double getConcurrency() {
        return concurrency;
    }

    public void analysis(long elapsed) {
        //最近counts 次的平均时间
        long all = time.addAndGet(elapsed);
        timeList.add(elapsed);
        long now = System.currentTimeMillis();
        times.add(Long.parseLong(RpcContext.getContext().getAttachment(TianchiRpcContants.BEGIN_KEY)));
        double size = timeList.size();
        long start = times.get(0);
        nowAvg = all / size;
        double v1 = (now-start)/nowAvg;
        double _concurrency = CodingApiLoadBalance.POOL_SIZE/v1;
        concurrencys.add(_concurrency);
        double count = 0.0d;
        for(double val:concurrencys){
            count+=val;
        }
        concurrency = count/concurrencys.size();
        if (size >= CodingApiLoadBalance.POOL_SIZE) {
            long one = timeList.get(0);
            time.addAndGet(-one);
            timeList.remove(0);
            times.remove(0);
            concurrencys.remove(0);
        }
    }
}
